import 'package:flutter/material.dart';

class SpotTradeScreen extends StatefulWidget {
  const SpotTradeScreen({super.key});

  @override
  State<SpotTradeScreen> createState() => _SpotTradeScreenState();
}

class _SpotTradeScreenState extends State<SpotTradeScreen> {
  String selectedFromCurrency = 'USDT'; // 稳定币
  String selectedToCurrency = 'HRC'; // 非遗币
  final TextEditingController fromAmountController = TextEditingController();
  final TextEditingController toAmountController = TextEditingController();
  double slippage = 0.5; // 滑点设置，默认0.5%
  
  // 稳定币列表
  final List<String> stableCoins = ['USDT', 'USDC', 'DAI', 'BUSD'];
  // 非遗相关币种列表
  final List<String> heritageCoins = ['HRC', 'NFT', 'ART', 'CULTURE'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF8F9FA),
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        toolbarHeight: 0, // 隐藏AppBar
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 交易对信息卡片
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 10,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Text(
                            '$selectedToCurrency/$selectedFromCurrency',
                            style: const TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF1A1A1A),
                            ),
                          ),
                          const SizedBox(width: 8),
                          // 滑点设置按钮移到这里
                          GestureDetector(
                            onTap: () => _showSlippageSettings(),
                            child: Container(
                              padding: const EdgeInsets.all(4),
                              decoration: BoxDecoration(
                                color: const Color(0xFF1890FF).withOpacity(0.1),
                                borderRadius: BorderRadius.circular(4),
                              ),
                              child: const Icon(
                                Icons.settings,
                                size: 16,
                                color: Color(0xFF1890FF),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          color: const Color(0xFF52C41A).withOpacity(0.1),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: const Text(
                          '+2.45%',
                          style: TextStyle(
                            color: Color(0xFF52C41A),
                            fontSize: 12,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  const Text(
                    '1.2345',
                    style: TextStyle(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color: Color(0xFF52C41A),
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '汇率: 1 $selectedToCurrency = 1.2345 $selectedFromCurrency',
                    style: const TextStyle(
                      fontSize: 14,
                      color: Color(0xFF8C8C8C),
                    ),
                  ),
                  const SizedBox(height: 8),
                  // 滑点显示
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: const Color(0xFF1890FF).withOpacity(0.1),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      '滑点: ${slippage.toStringAsFixed(1)}%',
                      style: const TextStyle(
                        color: Color(0xFF1890FF),
                        fontSize: 12,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 20),
            
            // 交易表单
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(12),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 10,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    'Swap 兑换',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: Color(0xFF1A1A1A),
                    ),
                  ),
                  const SizedBox(height: 16),
                  
                  // 买入部分（调换顺序）
                  const Text(
                    '买入',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFF595959),
                    ),
                  ),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      // 金额输入
                      Expanded(
                        child: TextField(
                          controller: fromAmountController,
                          keyboardType: TextInputType.number,
                          decoration: InputDecoration(
                            hintText: '请输入买入金额',
                            hintStyle: const TextStyle(
                              color: Color(0xFFBFBFBF),
                              fontSize: 14,
                            ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8),
                              borderSide: const BorderSide(color: Color(0xFFE8E8E8)),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8),
                              borderSide: const BorderSide(color: Color(0xFFE8E8E8)),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8),
                              borderSide: const BorderSide(color: Color(0xFF1890FF)),
                            ),
                            contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                          ),
                        ),
                      ),
                      const SizedBox(width: 12),
                      // 币种选择（稳定币）
                      GestureDetector(
                        onTap: () => _showCurrencySelector(true),
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                          decoration: BoxDecoration(
                            color: const Color(0xFFF5F5F5),
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(color: const Color(0xFFE8E8E8)),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                selectedFromCurrency,
                                style: const TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w500,
                                  color: Color(0xFF1A1A1A),
                                ),
                              ),
                              const SizedBox(width: 4),
                              const Icon(
                                Icons.keyboard_arrow_down,
                                size: 16,
                                color: Color(0xFF8C8C8C),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        '可用余额',
                        style: TextStyle(
                          fontSize: 12,
                          color: Color(0xFF8C8C8C),
                        ),
                      ),
                      Text(
                        '1,234.56 $selectedFromCurrency',
                        style: const TextStyle(
                          fontSize: 12,
                          color: Color(0xFF1A1A1A),
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                  
                  const SizedBox(height: 20),
                  
                  // 兑换图标
                  Center(
                    child: GestureDetector(
                      onTap: () {
                        // 交换币种
                        setState(() {
                          final temp = selectedFromCurrency;
                          selectedFromCurrency = selectedToCurrency;
                          selectedToCurrency = temp;
                          
                          final tempAmount = fromAmountController.text;
                          fromAmountController.text = toAmountController.text;
                          toAmountController.text = tempAmount;
                        });
                      },
                      child: Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          color: const Color(0xFF1890FF).withOpacity(0.1),
                          borderRadius: BorderRadius.circular(20),
                        ),
                        child: const Icon(
                          Icons.swap_vert,
                          color: Color(0xFF1890FF),
                          size: 20,
                        ),
                      ),
                    ),
                  ),
                  
                  const SizedBox(height: 20),
                  
                  // 卖出部分（调换顺序）
                  const Text(
                    '卖出',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFF595959),
                    ),
                  ),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      // 金额输入
                      Expanded(
                        child: TextField(
                          controller: toAmountController,
                          keyboardType: TextInputType.number,
                          decoration: InputDecoration(
                            hintText: '预计卖出获得',
                            hintStyle: const TextStyle(
                              color: Color(0xFFBFBFBF),
                              fontSize: 14,
                            ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8),
                              borderSide: const BorderSide(color: Color(0xFFE8E8E8)),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8),
                              borderSide: const BorderSide(color: Color(0xFFE8E8E8)),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(8),
                              borderSide: const BorderSide(color: Color(0xFF1890FF)),
                            ),
                            contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                          ),
                        ),
                      ),
                      const SizedBox(width: 12),
                      // 币种选择（非遗币）
                      GestureDetector(
                        onTap: () => _showCurrencySelector(false),
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
                          decoration: BoxDecoration(
                            color: const Color(0xFFF5F5F5),
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(color: const Color(0xFFE8E8E8)),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                selectedToCurrency,
                                style: const TextStyle(
                                  fontSize: 14,
                                  fontWeight: FontWeight.w500,
                                  color: Color(0xFF1A1A1A),
                                ),
                              ),
                              const SizedBox(width: 4),
                              const Icon(
                                Icons.keyboard_arrow_down,
                                size: 16,
                                color: Color(0xFF8C8C8C),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text(
                        '可用余额',
                        style: TextStyle(
                          fontSize: 12,
                          color: Color(0xFF8C8C8C),
                        ),
                      ),
                      Text(
                        '0.0234 $selectedToCurrency',
                        style: const TextStyle(
                          fontSize: 12,
                          color: Color(0xFF1A1A1A),
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                  
                  const SizedBox(height: 16),
                  
                  // 交易信息
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: const Color(0xFFF8F9FA),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text(
                              '汇率',
                              style: TextStyle(
                                fontSize: 12,
                                color: Color(0xFF8C8C8C),
                              ),
                            ),
                            Text(
                              '1 $selectedToCurrency = 1.2345 $selectedFromCurrency',
                              style: const TextStyle(
                                fontSize: 12,
                                color: Color(0xFF1A1A1A),
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 8),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text(
                              '滑点容忍度',
                              style: TextStyle(
                                fontSize: 12,
                                color: Color(0xFF8C8C8C),
                              ),
                            ),
                            Text(
                              '${slippage.toStringAsFixed(1)}%',
                              style: const TextStyle(
                                fontSize: 12,
                                color: Color(0xFF1A1A1A),
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(height: 8),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            const Text(
                              '最小接收',
                              style: TextStyle(
                                fontSize: 12,
                                color: Color(0xFF8C8C8C),
                              ),
                            ),
                            Text(
                              '0.9876 $selectedToCurrency',
                              style: const TextStyle(
                                fontSize: 12,
                                color: Color(0xFF1A1A1A),
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                  
                  const SizedBox(height: 24),
                  
                  // 交易按钮
                  Container(
                    width: double.infinity,
                    height: 48,
                    decoration: BoxDecoration(
                      gradient: const LinearGradient(
                        colors: [Color(0xFF1890FF), Color(0xFF096DD9)],
                        begin: Alignment.centerLeft,
                        end: Alignment.centerRight,
                      ),
                      borderRadius: BorderRadius.circular(12),
                      boxShadow: [
                        BoxShadow(
                          color: const Color(0xFF1890FF).withOpacity(0.3),
                          blurRadius: 6,
                          offset: const Offset(0, 3),
                        ),
                      ],
                    ),
                    child: ElevatedButton(
                      onPressed: () {
                        // 兑换逻辑
                        _performSwap();
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.transparent,
                        shadowColor: Colors.transparent,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: const Text(
                        '闪兑',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  // 显示滑点设置对话框
  void _showSlippageSettings() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('滑点设置'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text('选择滑点容忍度'),
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  _buildSlippageButton(0.1),
                  _buildSlippageButton(0.5),
                  _buildSlippageButton(1.0),
                  _buildSlippageButton(3.0),
                ],
              ),
              const SizedBox(height: 16),
              TextField(
                keyboardType: TextInputType.number,
                decoration: const InputDecoration(
                  labelText: '自定义滑点 (%)',
                  border: OutlineInputBorder(),
                ),
                onChanged: (value) {
                  final customSlippage = double.tryParse(value);
                  if (customSlippage != null && customSlippage >= 0 && customSlippage <= 50) {
                    setState(() {
                      slippage = customSlippage;
                    });
                  }
                },
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('确认'),
            ),
          ],
        );
      },
    );
  }
  
  // 滑点按钮
  Widget _buildSlippageButton(double value) {
    final isSelected = slippage == value;
    return GestureDetector(
      onTap: () {
        setState(() {
          slippage = value;
        });
      },
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: isSelected ? const Color(0xFF1890FF) : Colors.grey[200],
          borderRadius: BorderRadius.circular(6),
        ),
        child: Text(
          '${value.toStringAsFixed(1)}%',
          style: TextStyle(
            color: isSelected ? Colors.white : Colors.black,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }
  
  // 显示币种选择器
  void _showCurrencySelector(bool isFromCurrency) {
    final currencies = isFromCurrency ? stableCoins : heritageCoins;
    final title = isFromCurrency ? '选择稳定币' : '选择非遗币种';
    
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                title,
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.w600,
                ),
              ),
              const SizedBox(height: 16),
              ...currencies.map((currency) => ListTile(
                title: Text(currency),
                subtitle: Text(_getCurrencyDescription(currency)),
                onTap: () {
                  setState(() {
                    if (isFromCurrency) {
                      selectedFromCurrency = currency;
                    } else {
                      selectedToCurrency = currency;
                    }
                  });
                  Navigator.pop(context);
                },
              )).toList(),
            ],
          ),
        );
      },
    );
  }
  
  // 获取币种描述
  String _getCurrencyDescription(String currency) {
    switch (currency) {
      case 'USDT':
        return 'Tether USD - 美元稳定币';
      case 'USDC':
        return 'USD Coin - 美元稳定币';
      case 'DAI':
        return 'Dai - 去中心化稳定币';
      case 'BUSD':
        return 'Binance USD - 币安美元稳定币';
      case 'HRC':
        return 'Heritage Coin - 非遗传承币';
      case 'NFT':
        return 'Non-Fungible Token - 非同质化代币';
      case 'ART':
        return 'Art Token - 艺术品代币';
      case 'CULTURE':
        return 'Culture Token - 文化代币';
      default:
        return '';
    }
  }
  
  // 执行兑换
  void _performSwap() {
    if (fromAmountController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入兑换金额')),
      );
      return;
    }
    
    // 显示确认对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认兑换'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('支付: ${fromAmountController.text} $selectedFromCurrency'),
              Text('接收: ${toAmountController.text} $selectedToCurrency'),
              Text('汇率: 1 $selectedToCurrency = 1.2345 $selectedFromCurrency'),
              Text('滑点: ${slippage.toStringAsFixed(1)}%'),
              const SizedBox(height: 8),
              const Text(
                '请确认交易信息无误',
                style: TextStyle(
                  color: Color(0xFF8C8C8C),
                  fontSize: 12,
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
                // 执行兑换逻辑
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('兑换成功！')),
                );
              },
              child: const Text('确认兑换'),
            ),
          ],
        );
      },
    );
  }
}